<?php
namespace api\modules\v1\controllers\trade;
use Yii;
use api\modules\v1\controllers\CoreController;
use common\models\trade\TradeWithdrawModel;
use api\modules\models\finance\Balance;
use api\modules\models\finance\WithdrawLog;
use api\modules\models\member\Member;
use common\models\platform\SettingModel;
/*
	提现
*/

class WithdrawController extends CoreController
{
	/* 
		提现配置信息
		* b_type 
	*/
	public function actionWithdraw_conf()
	{
		if($this->request('b_type'))
		{
			$data = TradeWithdrawModel::find()->where(['mch_id'=>MCHID,'b_type'=>$this->request('b_type')])->asarray()->one();
			if(!$data) $this->error('请先配置提币规则');
			unset($data['condition_group']);
			unset($data['condition_rule']);	
			$bInfo = Balance::getBalance($this->_memberId,$data['b_type']);
			$data['balance'] = $bInfo['balance'];
			$data['type_name'] = $bInfo['type_name'];
			if($this->request('lang')=='en') $data['type_name'] = Balance::$typeNameEn[$data['b_type']];					
		}else
		{
			$data = TradeWithdrawModel::find()->where(['mch_id'=>MCHID])->asarray()->all();
			if(!$data) $this->error('请先配置提币规则');
			foreach($data as &$val)
			{
				unset($val['condition_group']);
				unset($val['condition_rule']);
				$bInfo = Balance::getBalance($this->_memberId,$val['b_type']);
				$val['balance'] = $bInfo['balance'];
				$val['type_name'] = $bInfo['type_name'];
				if($this->request('lang')=='en') $val['type_name'] = Balance::$typeNameEn[$val['b_type']];
			}			
		}
		$this->out('提现配置信息',$data);
	}


	/*
		提现申请
		* b_type 提现的帐本
		* password 交易密码
		* money  提现的金额
		* type   收款类型 wallet wechat alipay bank
		* address 收款类型为 wallet 是传入 
		* wechat 收款类型为wechat时传入
		* alipay 收款为alipay 时传入
		* bank_info 收款为bank时传入
	*/
	public function actionApply()
	{
		try{
			$transaction = Yii::$app->db->beginTransaction();

			## 配置信息
			$conf = TradeWithdrawModel::find()->where(['mch_id'=>MCHID,'b_type'=>$this->request('b_type')])->asarray()->one();
			$res = $this->withdrawCondition($conf);
			if(!$res['state']) $this->error($res['msg']);

			## 生成日志
			if(!$logId = $this->addWithdrawLog($this->request,$conf,$res['bInfo'])) throw new \Exception("日志添加失败");
			
			//扣除账本金额
			$btype = $this->request('b_type');
			$money = $this->request('money');
			$res = Balance::reduceBalance($this->_memberId,$btype,$money,20,$logId);
			if(!$res['state']) throw new \Exception($res['msg']);

			$transaction->commit();
			$this->out('操作成功');
		}catch(\Exception $e)
		{
			$transaction->rollback();
			$this->error($e->getMessage());
		}
	}


	private function withdrawCondition($conf)
	{
		$money = $this->request('money',0);
		if(md5($this->request('password'))!=$this->_member['paypwd']) $this->error('密码错误');
		if(!$this->_member['state'] || $this->_member['user_type']==2) return ['state'=>false,'msg'=>'你暂不能此操作'];
		if($money<=0) return ['state'=>false,'msg'=>'金额不能小于0'];
		if($this->_member['balance_due']>0) return ['state'=> false,'msg'=>'有欠款没清'];  
		
		if(!$conf['state']) return ['state'=>false,'msg'=>'暂不能提现'];
		if(!$conf) return ['state'=>false,'msg'=>'配置信息有误'];
		if($conf['min_num'] > 0 && $conf['min_num'] > $money) return ['state'=>false,'msg'=>'提现金额不能小于'.$conf['min_num']];
		if($conf['max_num'] > 0 && $conf['max_num'] < $money) return ['state'=>false,'msg'=>'提现金额不能大于'.$conf['max_num']];
		if($conf['multiple'] > 0 && $money%$conf['multiple']) return ['state'=>false,'msg'=>'提现金额要为'.$conf['multiple'].'的倍数'];

		$where = ['member_id'=>$this->_memberId];
		$st = mktime(0,0,0,date('m'),date('d'),date('Y'));
		$num = WithdrawLog::find()->where($where)->andWhere(['>=','create_time',$st])->count();
		if($num>0) $this->error('每天只能提一笔');
		if(date("H")<6) $this->error('6点之前不能提现');


		$type = $this->request('type','wallet');
		if($type == 'wallet')
		{
			if(!$this->request('address')) return ['state'=>false,'msg'=>'提币地址不能为空'];
			if(strpos($this->request('address'),'0x') !== 0) return ['state'=>false,'msg'=>'提币地址不正确'];  
			if(strlen($this->request('address')) != 42) return ['state'=>false,'msg'=>'提币地址有误']; 
			$member = Member::find()->where(["address"=>$this->request('address')])->count();
			if($member) return ['state'=>false,'msg'=>'提币地址不能为本系统生成的']; 	
		}
				
		$bInfo = Balance::getBalance($this->_memberId,$this->request('b_type'));
		if($bInfo['balance']<$this->request('money'))
			return ['state'=>false,'msg'=>'余额不足'];

		return ['state'=>true,'msg'=>'ok','bInfo'=>$bInfo];
	}	


	private function addWithdrawLog($params,$conf,$bInfo)
	{
		$data = array();
		$data['member_id'] = $this->_memberId;
		$data['money'] = $params['money'];
		$data['b_type'] = $params['b_type'];
		$data['type'] = isset($params['type'])?$params['type']:'wallet';
		$data['state'] = 1;
		$data['service_charge'] = round($conf['rate']*$params['money']/100,2);
		$data['create_time'] = time();
		if($data['type'] == 'wallet') $data['collect_info'] = $params['address'];
		$data['price'] = SettingModel::getValue('price','lcl');  

		$model = new WithdrawLog;
		if(!$model->load($data,'') || !$model->save()){
			throw new \Exception($this->model_errors($model->errors));
			return false;
		} 
		$id = Yii::$app->db->getLastInsertId();
		return $id;
	}


	/* 
		* 提现记录
		* page 
		* page_size
		* b_type 选填
	*/

	public function actionWithdraw_list()
	{
		$where = array();
		$where['where'] = ['member_id'=>$this->_memberId];
		if($this->request('b_type')) $where['where']['b_type'] = $this->request('b_type');
		$params = array(
			'field' => ['*'],
			'page'	=> $this->request('page',1),
			'limit' => $this->request('page_size',10),
			'order' => 'id DESC'
		);
		$data = WithdrawLog::withdrawList($where,$params,['collect']);
		$this->out('提现信息',$data);
	}


}